package com.tus.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;

@Slf4j
public class FileHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final List<Handler> handlers;

    public FileHandler(List<Handler> handlers) {
        this.handlers = handlers;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
        String uri = req.uri();
        boolean notExist = true;
        for (Handler handler : handlers) {
            String pathPrefix = handler.getPathPrefix();
            if (uri.startsWith(pathPrefix)) {
                notExist = false;
                handler.execute(ctx, req);
            }
        }
        if (notExist) {
            Handler.sendError(ctx, NOT_FOUND, "Not Found");
        }
    }
}
